//
//  CZOAuthViewController.swift
//  微博
//
//  Created by 范承志 on 16/6/11.
//  Copyright © 2016年 fanchengzhi. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD

class CZOAuthViewController: UIViewController {

    override func loadView() {
        view = WebView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 监听事件
    // 取消
    @objc private func cancelClick(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    // 自动填充
    @objc private func autoFillClick(){
        let jsString = "document.getElementById('userId').value='\(CZWebName)',document.getElementById('passwd').value='\(CZWebPassword)'"
        //js注入
        WebView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.white
        setupNav()
    }
    
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(highlightedImgName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(highlightedImgName: nil, title: "自动填充", target: self, action: #selector(autoFillClick))
        navigationItem.title = "微博登录"
    }
    //懒加载控件
    private lazy var WebView: UIWebView = {
        //url
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(CZAppKey)&redirect_uri=\(CZAppHuiDiaoYe)")!
        //request
        let request = URLRequest(url: url)
        let view = UIWebView()
        view.delegate = self
        view.loadRequest(request)
        return view
    }()
}
//MARK: - UIWebViewDelegate
extension CZOAuthViewController: UIWebViewDelegate{
    //监听UIWebView将要加载的request 默认不是实现
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //urlstring
        let urlString = request.url?.absoluteString
        //判断urlString不为nil 而且前缀包含我们的回调页
        if let u = urlString, u.hasPrefix(CZAppHuiDiaoYe){
            //请求参数
            let query = request.url?.query
            //判断请求参数是否为nil
            if let q = query{
                //截取得到code
                let code = q.substring(from: "code=".endIndex)
                
                CZUserAccountViewModel.sharedTools.getUserAccount(code:code,finish:{(isSuccess) in
                    
                    if !isSuccess{
                        print("请求失败")
                        return
                    }
                    print("请求成功")
                    //结束动画
                    SVProgressHUD.dismiss()
                    self.dismiss(animated: false, completion: { 
                        
                        //发通知跳转到欢迎界面
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CZSWITCHROOTVCNOTI), object: nil)
                    })
                })
                //不在叫他加载授权界面
                return false
            }
        }
        return true
    }
    
    //已经开始完成
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        //开始动画
        SVProgressHUD.show()
    }
    
    //已经结束完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        //结束动画
        SVProgressHUD.dismiss()
    }
}
